﻿function Get-TSMScript {    
    <#
        .SYNOPSIS
            Get TSM scripts
                    
        .DESCRIPTION
            The Get-TSMScript returns nodes registered on the TSM server
            
        .PARAMETER Script
            Script name to query

        .PARAMETER Rollup
            Roll up query results into individual script objects

        .EXAMPLE
            Get-TSMScript -Rollup

        .NOTES
            Contributors:  David Seibel
            Last Revision Date: 09/01/2015

    #>
    [CmdletBinding()]
    Param(
        [Parameter(Position=0)]
        [string]$Script,

        [switch]$Rollup
    )
    
    $whereProps = @()
    $whereProps += [PSCustomObject]@{ "Column" = "NAME"; "Operator" = "LIKE"; "Value" = $Script }

    $query = Format-TSMQuery -Table "SCRIPTS" -Where $whereProps -OrderBy "NAME,LINE"
    $result = Invoke-TSMCommand -Command $query

    $defaultDisplaySet = 'NAME','LINE','COMMAND'
    $typeDefinitions = @{
                        "LINE"     = [Int32]
                        "CHG_TIME" = [DateTime]
                        }

    $results = Format-TSMData -Data $result -TypeDefinitions $typeDefinitions -DefaultDisplaySet $defaultDisplaySet

    if ($Rollup) {
        $finalResults = @()
        foreach ($grouping in ($results | Group-Object -Property Name)) {
            $temp = New-Object PSObject
            $temp | Add-Member -MemberType NoteProperty -Name "Name"        -Value $grouping.Name
            $temp | Add-Member -MemberType NoteProperty -Name "Description" -Value ($grouping.Group | Where-Object {$_.Line -eq 0}).Command
            $temp | Add-Member -MemberType NoteProperty -Name "Script"      -Value (($grouping.Group | Where-Object {$_.Line -ne 0}).Command -join "`n")
            $finalResults += $temp
        }
    } else {
        $finalResults = $results
    }

    return $finalResults
}